package controller;

import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import base_classes.Kurs;
import base_classes.User;

import dao.UserDao;
import dao.KursDao;

import org.hibernate.Hibernate;

/** 
 * Controller to generate the Home Page basics to be rendered by a view. 
 * It extends the convenience class AbstractController that encapsulates most 
 * of the drudgery involved in handling HTTP requests. 
 * @author josef@dr-schneeberger.de
 */
public class SaveStudentKurs extends AbstractController {

	
	private KursDao kursDao;
	private UserDao userDao;
	Set<base_classes.Kurs> setsk = new HashSet<base_classes.Kurs>(); 
	Set<base_classes.Kurs> setskdel = new HashSet<base_classes.Kurs>();

	public KursDao getKursDao() {
		return kursDao;
	}
	
	public void setKursDao(KursDao kursDao) {
		this.kursDao = kursDao;
	}
	
	public UserDao getUserDao() {
		return userDao;
	}
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	protected ModelAndView handleRequestInternal(
			HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) throws Exception {
		httpServletRequest.setCharacterEncoding("UTF-8");
		ModelAndView mv = new ModelAndView();
		int idKurs;
		int idUser;
		int idAction;
		
		idKurs = Integer.parseInt(httpServletRequest.getParameter("id"));
		idUser = Integer.parseInt(httpServletRequest.getParameter("user"));
		idAction = Integer.parseInt(httpServletRequest.getParameter("action"));
		
		User user = userDao.findById(idUser);
		Kurs kurs = kursDao.findById(idKurs);
		if (idKurs != 0 && idUser != 0 && idAction !=0) {
			setsk = user.getKurse();
			
			if (idAction == 1) { //delete
				Iterator iterate = setsk.iterator();
				while (iterate.hasNext()) {
					Kurs k = (Kurs) iterate.next();
					if (idKurs == k.getIdKurs()) {
						setsk.remove(k);						
					}	
				}
				userDao.modify(idUser, setsk);
				mv.addObject("title", "Erfolgreich");
				mv.addObject("message", "Sie haben diesen Kurs verlassen");
			}
			else {
				setsk.add(kurs);
				userDao.modify(idUser, setsk);
				mv.addObject("title", "Erfolgreich");
				mv.addObject("message", "Sie haben sich erfolgreich in diesen Kurs eingeschrieben");	
			}
		}
		else {
				mv.addObject("title", "Fehler");
				mv.addObject("message", "Fehler im Programm");

			}
		
		mv.setViewName("save-kursstudent");
		return mv;
	}

}